<?php

namespace App\Store\Services\Order;

use App\Common\Services\Store\Common as StoreCommon;
use App\Store\Models\Account\Account;
use App\Store\Models\Account\SiteStore;
use App\Store\Models\Basic\PaytypeList;
use App\Store\Models\Goods\GoodsGlodprice;
use App\Store\Models\Sysset\Commission\Recovery;
use Illuminate\Http\Request;
use App\Store\Models\Order\OrderRecovery as RecoveryModel;

class OrderRecovery
{

    /**
     * 回收开单计算业绩和提成
     */
    public static function computePerformanceAndCommission(array $recoverygoodslist_new)
    {

        //换货旧料提成
        $is_open_added_recovery = SiteStore::where(['cp_id' => $recoverygoodslist_new[0]['cp_id'], 'id' => $recoverygoodslist_new[0]['store_id']])->value('is_open_added_recovery');

        foreach ($recoverygoodslist_new as &$rgv) {
            if ($rgv['recovery_type'] == 1) {

                $lastprice = GoodsGlodprice::where(['cp_id' => $rgv['cp_id'], 'store_id' => $rgv['store_id'], 'goods_category_id' => $rgv['goods_category_id'], 'is_del' => 1])
                    ->where('date_str', '<=', date('Y-m-d'))->orderBy('date_str', 'desc')->first();

                $rgv['sales_price'] = $lastprice ? $lastprice->sales_price : 0;
                $rgv['old_recovery_price'] = $lastprice ? $lastprice->back_company_price : 0;

                if ($rgv['price'] > $rgv['sales_price']) {
                    $rgv['recovery_type_price'] = 1;
                } else {
                    if ($rgv['price'] <= $rgv['old_recovery_price']) {
                        $rgv['recovery_type_price'] = 3;
                    } else {
                        $rgv['recovery_type_price'] = 2;
                    }

                }
                $rgv['performance'] = $rgv['money'];

                if ($is_open_added_recovery == 2 && $rgv['recovery_type_price'] == 1) {

                     // 商品回收的金额-（（单价-料价）*（数量*（商品的金重-损耗的金重）)*折扣）
                    $rgv['performance'] = $rgv['performance'] - intval(($rgv['price'] - $rgv['old_recovery_price']) * (bcmul($rgv['count'], ($rgv['weight'] - $rgv['loss_weight']), 3)) * ($rgv['discount'] > 0 ? $rgv['discount'] : 100) / 100);

                    $rgv['performance'] =$rgv['performance']>0?$rgv['performance']:0;
                }


                $weight = bcmul($rgv['count'], ($rgv['weight'] - $rgv['loss_weight']), 3);

            } else {
                $rgv['recovery_type_price'] = 0;
                $rgv['performance'] = $rgv['money'];
                // $weight=$rgv['weight']*$rgv['count']-$rgv['loss_weight'];
                $weight = bcmul($rgv['count'], ($rgv['weight'] - $rgv['loss_weight']), 3);
            }

           // echo $weight;exit;
            //提成
            $ruleinfo = Recovery::where([['goods_category_id', $rgv['goods_category_id']], ['cp_id', $rgv['cp_id']], ['store_id', $rgv['store_id']],
                ['gram_min', '<=', $weight], ['gram_max', '>=', $weight], ['is_del', 1]])->first();
            if ($ruleinfo) {
                $rgv['commission1'] = intval($weight * $ruleinfo['money']);
            } else {
                $rgv['commission1'] = 0;
            }
        }
        return $recoverygoodslist_new;
    }

    /**
     * 纯回收开单打印数据
     * @param $orderid
     * @param $request
     * @param $isPrint
     * @return array
     */
    public static function getOrderPrintData($orderid, $request,$isPrint=false)
    {

        if($isPrint==false){
            $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        }else{
            $accountinfo = Account::query()
                ->where('id',$request->account_id)
                ->first();
            $accountinfo =empty($accountinfo)?[]: $accountinfo->toArray();
        }

        $withinfo = [
            'memberinfo',
            'shoppingaccountinfo1',
            'shoppingaccountinfo2',
            'storeinfo',
            'goodslist',
            'companyinfo',
        ];
        $info = RecoveryModel::with($withinfo)
            ->where(['id' => $orderid, 'is_del' => 1])->first();

        if ($info) {
            $info = $info->toArray();
            $goodsdata = [];
            $count_total = 0;
            $weight_total = 0;

            foreach ($info['goodslist'] as $k => $v) {
                $goodsdata[] = [
                    'goods_sn_code' => '旧料:' . $v['goods_sn_code'],
                    'goods_name' => $v['goods_catefory_name']??'',
                    'piece_weight' => $v['weight'],//'按件回收的重量'
                    'label_price' => $v['d_price'] / 100,
                    'cost_price' => '',
                    'pieceprice_fee' => '',
                    'gold_weight1' => $v['weight'],//'按件按克回收重量'
                    'gold_weight2' => '',
                    'gold_weight3' => ($v['recovery_type'] == 1) ? $v['weight'] : '',//旧料按克回收的回收重量
                    'gold_weight4' => $v['weight'], //-旧料回收按克按件的回收重量
                    'add_fee1' => '',
                    'add_fee2' => '',
                    'gemstone_fee1' => '',
                    'gemstone_fee2' => '',
                    'costglod_price' => '',
                    'costglod_price2' => $v['price'] / 100,
                    'discount_money' => '',
                    'real_total_money' => -($v['money'] / 100),//'开单-回收金额（负数显示）'
                    'capital_real_total_money' => '',
                    'style_name' => '',
                    's_no' => '',
                    'content' => '',
                    'count' => $v['count'],//'旧料的数量'
                    'craft_name' => '',
                    'c_no' => '',
                    'brand_name' => '',
                    'cf_no' => '',
                    'cf_no_gia' => '',
                    'main_stone_weigth' => '',
                    'other_stone_weigth' => '',
                    'main_stone_count' => '',
                    'other_stone_count' => '',
                    'color' => '',
                    'clarity' => '',
                    'cut' => '',
                    'pricetype_name' => '',
                    'remark' => '',
                    'discount' => $v['discount'],//'旧料的折扣'
                    'cost_price_discount' => '',
                    'glod_price_discount' => '',
                    'category_name' => $v['goods_catefory_name'],//'旧料品类'
                    'dold_price' => $v['dold_price'] / 100,//'单个旧料的折旧单价'
                    'dold_fee' => $v['dold_fee'] / 100,//'单个旧料的折旧工费'
                    'loss_weight' => $v['loss_weight'],//'单个旧料的损耗重量'
                    'truncate_glod_weight' => '',
                    'truncate_glod_money' => '',
                    'total_money' => '',
                    'old_catefory_name' => $v['goods_catefory_name'],//'旧料品类'
                    'recovery_weight' => $v['weight'],
                    'recovery_price' => $v['price'] / 100,
                    'recovery_d_price' => $v['d_price'] / 100,//'回收标价'
                    'recovery_money' => $v['money'] / 100,//'回收金额',
                    'sendgoods_name' => '',
                    'recovery_type' => $v['recovery_type'] == 1 ? '按克' : '标价',
                    'change_type' => $v['change_type'] == 1 ? '回收' : '上柜',
                ];
                $count_total = bcadd($count_total, $v['count']);
                $weight_total = bcadd($weight_total, $v['weight'], 3);
            }

            if ($info['pay_type_id'] == -1) {
                $paytype_name = '';
//                {"paytype_16":140000,"paytype_9":5600,"paytype_7":200000}
                foreach ($info['mixed_payment'] as $k => $va) {
                    $paytype_id = substr($k, 8);
                    $va = $va / 100;
                    $paytype_name .= PaytypeList::where('id', '=', $paytype_id)->value('paytype_name') . ":-" . $va . ' ';
                };
            } else {
                $paytype_name = $info['pay_type_name'] ?? '';
            }

            $allinfo = [
                'cost_price_total' => '',
                'real_money_total' => $info['total_money']>0? -($info['total_money'] / 100):0,
                'capital_real_money_total' => $info['total_money']>0? ('负'.self::num_to_rmb($info['total_money'] / 100)):'',
                'paytype_name' => $paytype_name,
                'order_sn' => $info['order_sn'],
                'real_name' => $accountinfo['real_name'],
                'store_name' => $info['storeinfo']['store_name'] ?? '',
                'address_area' => $info['storeinfo']['address_area'] ?? '',
                'contact_phone' => $info['storeinfo']['contact_phone']?? '',
                'count_total' => $count_total,
                'weight_total' => $weight_total,
                'remark' => '',
                'total_discounts' => '',
                'shop_account' =>$info['shoppingaccountinfo1']['real_name']??'',
                'assistant_shop_account' => $info['shoppingaccountinfo2']['real_name']??'',
                'changegoods_money' => '',
                'round_down_money' => '',
                'order_discount' => '',
                'total_money' => $info['total_money']>0? -($info['total_money']/100):0,
                'coupon_money' => '',
                'mem_real_name' => !empty($info['memberinfo']) ? ($info['memberinfo']['real_name']??'' ): '',
                'mem_mobile' => !empty($info['memberinfo']) ? ($info['memberinfo']['mobile']??''): '',
                'mem_points' => ($info['issendpoints'] == 2 && $info['mem_id'] > 0) ? (($info['order_points']??0) + ($info['order_points_recovery']??0) + ($info['share_mem_send_points']??0)) : '',
                'mem_points_current' => !empty($info['memberinfo']) ? ($info['memberinfo']['points_current']?? '')  : '',
                'mem_lunar_bdate' =>!empty($info['memberinfo']) ? $info['memberinfo']['lunar_bdate'] : '',
                'mem_solar_bdate' =>!empty($info['memberinfo']) ?$info['memberinfo']['solar_bdate'] : '',
                'mem_card_no' =>!empty($info['memberinfo']) ? ($info['memberinfo']['mem_card_no']??'' ): '',
                'mem_pre_money' => !empty($info['memberinfo']) ?($info['memberinfo']['pre_money'] / 100 ): '',
                'balance_money' =>'',
                'pre_money' => '',
                'order_time' => date('Y-m-d H:i:s', $info['order_at']),
                'print_time' => date('Y-m-d H:i:s'),
                'order_type' => '纯回收开单',
            ];
            return ['info' => $allinfo, 'goodsdata' => $goodsdata];
        } else {
            return [];
        }


    }


    /**
     *  金额转大写
     * @param $num
     * @return string
     */
    public static function num_to_rmb($num)
    {

        $c1 = "零壹贰叁肆伍陆柒捌玖";
        $c2 = "分角元拾佰仟万拾佰仟亿";
        //精确到分后面就不要了，所以只留两个小数位
        $num = round($num, 2);

        //将数字转化为整数
        $num = $num * 100;
        if (strlen($num) > 10) {
            return "金额太大，请检查";
        }

        $i = 0;
        $c = "";
        while (1) {
            if ($i == 0) {
                //获取最后一位数字
                $n = substr($num, strlen($num) - 1, 1);
            } else {
                $n = $num % 10;
            }

            //每次将最后一位数字转化为中文
            $p1 = substr($c1, 3 * $n, 3);
            $p2 = substr($c2, 3 * $i, 3);
            if ($n != '0' || ($n == '0' && ($p2 == '亿' || $p2 == '万' || $p2 == '元'))) {
                $c = $p1 . $p2 . $c;
            } else {
                $c = $p1 . $c;
            }

            $i = $i + 1;
            //去掉数字最后一位了
            $num = $num / 10;
            $num = (int)$num;
            //结束循环
            if ($num == 0) {
                break;
            }

        }

        $j = 0;
        $slen = strlen($c);
        while ($j < $slen) {
            //utf8一个汉字相当3个字符
            $m = substr($c, $j, 6);
            //处理数字中很多0的情况,每次循环去掉一个汉字“零”
            if ($m == '零元' || $m == '零万' || $m == '零亿' || $m == '零零') {
                $left = substr($c, 0, $j);
                $right = substr($c, $j + 3);
                $c = $left . $right;
                $j = $j - 3;
                $slen = $slen - 3;
            }

            $j = $j + 3;
        }

        //这个是为了去掉类似23.0中最后一个“零”字
        if (substr($c, strlen($c) - 3, 3) == '零') {
            $c = substr($c, 0, strlen($c) - 3);
        }

        //将处理的汉字加上“整”
        if (empty($c)) {
            return "零元整";
        } else {
            return $c . "整";
        }

    }
}
